import json
import os
from typing import Any, Dict, List, Union

class FileHandler:
    @staticmethod
    def ensure_directory(directory: str) -> None:
        """确保目录存在"""
        os.makedirs(directory, exist_ok=True)
    
    @staticmethod
    def read_json(file_path: str, default_value: Any = None) -> Any:
        """读取JSON文件"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            return default_value
        except json.JSONDecodeError:
            return default_value
    
    @staticmethod
    def write_json(file_path: str, data: Union[Dict, List], ensure_dir: bool = True) -> bool:
        """写入JSON文件"""
        try:
            if ensure_dir:
                FileHandler.ensure_directory(os.path.dirname(file_path))
            
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"写入JSON文件失败: {str(e)}")
            return False 